package me.dwliu.springcloud.util;

import me.dwliu.springcloud.vo.User;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.ArrayList;
import java.util.List;

public class UserPermissionUtil {
    public static final String SERVICE_NAME = "x-user-serviceName";

    public static boolean verify(User user, ServletWebRequest request) {


        String url = request.getHeader(SERVICE_NAME);

        if (StringUtils.isEmpty(user)) {
            return false;
        } else {
            List<String> allowPermissionService = user.getAllowPermissionService();
            for (String ps : allowPermissionService) {
                if (url.equalsIgnoreCase(ps)) {
                    return true;
                }
            }
        }


        return false;
    }


    public static void permission(User user) {
        List<String> permission;
        if (user.getUsername().equals("admin")) {
            permission = new ArrayList<>();
            permission.add("client-server");
            permission.add("provider-server");
            user.setAllowPermissionService(permission);

        } else if (user.getUsername().equals("spring")) {
            permission = new ArrayList<>();
            permission.add("client-server");
            user.setAllowPermissionService(permission);
        } else {
            permission = new ArrayList<>();
            user.setAllowPermissionService(permission);
        }

    }

}
